package com.jeeplus.modules.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.api.req.ReqJson;
import com.jeeplus.modules.api.res.ResJson;
import com.jeeplus.modules.api.service.ApiService;
import com.jeeplus.modules.api.utils.*;

import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.msg.service.MsgService;
import com.jeeplus.modules.msgexample.entity.MsgExample;
import com.jeeplus.modules.msgexample.service.MsgExampleService;
import com.jeeplus.modules.sys.entity.DictValue;
import com.jeeplus.modules.sys.service.DictTypeService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * APP接口
 * @author Administrator
 *
 */
@CrossOrigin(origins = "*")
@Controller
@RequestMapping(value = "/api")
public class ApiController3 extends BaseController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private DictTypeService dictTypeService;
	@Autowired
	private MsgExampleService msgExampleService;
	@Autowired
	private MsgService msgService;
	@Autowired
	private ApiService apiService;
	private String wohuiId = "35278AE6B4E14F1F9582937C5C836453";
	/**
	 * 多多进宝推荐商品
	 * 进宝频道推广商品: 1-今日销量榜,3-相似商品推荐,4-猜你喜欢(和进宝网站精选一致),5-实时热销榜,6-实时收益榜。默认值5
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoGetrecommend")
	@ResponseBody
	public ResJson pinduoduoGetrecommend(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		res.put("mobile_url","");
		if (isBlank(req.getString("channel_type"))) {
			res.setResultNote("channel_type进宝频道推广商品渠道为空！");
			return res;
		}
		if (isBlank(req.getString("uid"))) {
			res.setResultNote("请先登录！");
			return res;
		}
		int page =0;
		int limit=0;
		if (isBlank(req.getString("pageNo"))) {
			page=1;
		}else{
			page = Integer.parseInt(req.getString("pageNo"));
		}
		if (isBlank(req.getString("pageSize"))) {
			limit=10;
		}else{
			limit = Integer.parseInt(req.getString("pageSize"));
		}
		req.put("offset",(page-1)*limit);
		req.put("limit",limit);
		Member member=memberService.get(req.getString("uid"));
		if(member==null){
			res.setResult("1");
			res.setResultNote("用户不存在");
			return res;
		}
		if(isBlank(member.getPddId())){
			//调用喵有券创建推广位接口给当前用户生成一个推广位id
			Map<String, String> params12 = Maps.newHashMap();
			params12.put("pdname", MiaoyouquanUtils.pdname);
			params12.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params12);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						member.setPddId(pidList.getJSONObject(0).getString("p_id"));
						memberService.save(member);
					}
				}
			}
		}
		Map<String, String> params10 = Maps.newHashMap();
		Map<String, String> params11 = Maps.newHashMap();
		params10.put("pid",member.getPddId());
		params10.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
		if (jsonObject10.containsKey("error_response")) {
			res.setResult("1");
			res.setResultNote("获取失败");
			return res;
		}
		if(jsonObject10.getJSONObject("authority_query_response").getString("bind").equals("0")){
			params11.put("channel_type","10");
			params11.put("p_id_list", "['"+member.getPddId()+"']");
			params11.put("generate_we_app","true");
			params11.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			JSONObject jsonObject11 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params11);
			if (jsonObject10.containsKey("error_response")) {
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}
			res.setResult("0");
			res.setResultNote("未授权！");
			JSONObject url= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("mobile_url",url.getString("url"));
			JSONObject wxpay= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("we_app_info",wxpay.getJSONObject("we_app_info"));
			res.setTotalCount(0);
			res.setTotalPage(0);
			res.setResult("0");
			res.setDataList(new JSONArray());
			res.setResultNote("查询成功");
			return res;
		}
		Map<String, String> params = Maps.newHashMap();
		params.put("pid",member.getPddId());
		params.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		params.put("channel_type",req.getString("channel_type"));
		params.put("offset",req.getString("offset"));
		params.put("limit",req.getString("limit"));
		JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.recommend, params);
		if(jsonObject.containsKey("error_response")){
			res.setResultNote("获取失败！");
			return res;
		}
		JSONArray jsonList = jsonObject.getJSONObject("goods_basic_detail_response").getJSONArray("list");
		JSONArray dataList4= new JSONArray();
		for(int i=0;i<jsonList.size();i++){
			// 遍历 jsonarray 数组，把每一个对象转成 json 对象
			JSONObject insertObj = jsonList.getJSONObject(i);
			JSONObject insertObj1 = new JSONObject();
			insertObj1.put("goods_name",insertObj.getString("goods_name"));
			insertObj1.put("goods_sign",insertObj.getString("goods_sign"));
			insertObj1.put("goods_image_url",insertObj.getString("goods_image_url"));
			insertObj1.put("min_normal_price",insertObj.getString("min_normal_price"));
			insertObj1.put("min_group_price",insertObj.getString("min_group_price"));
			insertObj1.put("sales_tip",insertObj.getString("sales_tip"));
//			float price=Float.valueOf(insertObj.getString("min_group_price"));
//			float discount=Float.valueOf(insertObj.getString("coupon_discount"));
//			float quanhoujia=price-discount;
//			insertObj1.put("quanhoujia_price",quanhoujia);
			insertObj1.put("goods_id",insertObj.getString("goods_id"));
			insertObj1.put("promotion_rate",insertObj.getString("promotion_rate"));
			insertObj1.put("unified_tags",insertObj.getString("unified_tags"));
			insertObj1.put("coupon_discount",insertObj.getString("coupon_discount"));
			if (insertObj.containsKey("predict_promotion_rate")&&insertObj.getString("predict_promotion_rate").equals("0")) {
				insertObj1.put("is_bj","true");
			}
			dataList4.add(insertObj1);
		}
		int Total=jsonObject.getJSONObject("goods_basic_detail_response").getIntValue("total");
		int zpage=Total/limit;
		int yushu=Total%limit;
		if(yushu>0){
			zpage=zpage+1;
		}
		res.setTotalCount(Total);
		res.setTotalPage(zpage);
		res.setResult("0");
		res.setDataList(dataList4);
		res.setResultNote("查询成功");
		return res;
	}
	/**
	 * 多多进宝搜索商品
	 * 排序方式:0-综合排序;1-按佣金比率升序;2-按佣金比例降序;3-按价格升序;4-按价格降序;5-按销量升序;6-按销量降序;7-优惠券金额排序升序;8-优惠券金额排序降序;9-券后价升序排序;10-券后价降序排序;11-按照加入多多进宝时间升序;12-按照加入多多进宝时间降序;13-按佣金金额升序排序;14-按佣金金额降序排序;15-店铺描述评分升序;16-店铺描述评分降序;17-店铺物流评分升序;18-店铺物流评分降序;19-店铺服务评分升序;20-店铺服务评分降序;27-描述评分击败同类店铺百分比升序，28-描述评分击败同类店铺百分比降序，29-物流评分击败同类店铺百分比升序，30-物流评分击败同类店铺百分比降序，31-服务评分击败同类店铺百分比升序，32-服务评分击败同类店铺百分比降序
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoSearchgoods")
	@ResponseBody
	public ResJson pinduoduoSearchgoods(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		res.put("mobile_url","");
		if (isBlank(req.getString("uid"))) {
			res.setResultNote("请先登录！");
			return res;
		}
		if (isBlank(req.getString("range_id"))) {
			res.setResultNote("查询类型不能为空！");
			return res;
		}
		if (isBlank(req.getString("range_id"))) {
			res.setResultNote("查询类型不能为空！");
			return res;
		}
		if (isBlank(req.getString("range_from"))) {
			res.setResultNote("查询开始值！");
			return res;
		}
		if (isBlank(req.getString("range_to"))) {
			res.setResultNote("查询结束值！");
			return res;
		}
		int page =0;
		int page_size=0;
		if (isBlank(req.getString("pageNo"))) {
			page=1;
		}else{
			page = Integer.parseInt(req.getString("pageNo"));
		}
		if (isBlank(req.getString("pageSize"))) {
			page_size=10;
		}else{
			page_size = Integer.parseInt(req.getString("pageSize"));
		}
		Member member=memberService.get(req.getString("uid"));
		if(member==null){
			res.setResult("1");
			res.setResultNote("用户不存在");
			return res;
		}
		if(isBlank(member.getPddId())){
			//调用喵有券创建推广位接口给当前用户生成一个推广位id
			Map<String, String> params12 = Maps.newHashMap();
			params12.put("pdname", MiaoyouquanUtils.pdname);
			params12.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params12);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						member.setPddId(pidList.getJSONObject(0).getString("p_id"));
						memberService.save(member);
					}
				}
			}
		}
		Map<String, String> params10 = Maps.newHashMap();
		Map<String, String> params11 = Maps.newHashMap();
		params10.put("pid",member.getPddId());
		params10.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
		if (jsonObject10.containsKey("error_response")) {
			res.setResult("1");
			res.setResultNote("获取失败");
			return res;
		}
		if(jsonObject10.getJSONObject("authority_query_response").getString("bind").equals("0")){
			params11.put("channel_type","10");
			params11.put("p_id_list", "['"+member.getPddId()+"']");
			params11.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			params11.put("generate_we_app","true");
			JSONObject jsonObject11 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params11);
			if (jsonObject10.containsKey("error_response")) {
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}
			res.setResult("0");
			res.setResultNote("未授权！");
			JSONObject url= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("mobile_url",url.getString("url"));
			JSONObject wxpay= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("we_app_info",wxpay.getJSONObject("we_app_info"));
			res.setTotalCount(0);
			res.setTotalPage(0);
			res.setResult("0");
			res.setDataList(new JSONArray());
			res.setResultNote("查询成功");
			return res;
		}
		Map<String, String> params = Maps.newHashMap();
		params.put("pid",member.getPddId());
		params.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		params.put("sort_type",req.getString("sortType"));
		String Str="[{'range_id':'"+req.getString("range_id")+"','range_from':'"+req.getString("range_from")+"','range_to':'"+req.getString("range_to")+"'}]";
		params.put("range_list", Str);
		params.put("page",String.valueOf(page));
		params.put("page_size",String.valueOf(page_size));
		String list_id= RandomStringUtils.randomAlphanumeric(33);
		params.put("list_id", req.getString("list_id"));
		JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.searchgoods, params);
		if(jsonObject.containsKey("error_response")){
			res.setResultNote("获取失败！");
			return res;
		}
		JSONArray jsonList = jsonObject.getJSONObject("goods_search_response").getJSONArray("goods_list");
		JSONArray dataList4= new JSONArray();
		for(int i=0;i<jsonList.size();i++){
			// 遍历 jsonarray 数组，把每一个对象转成 json 对象
			JSONObject insertObj = jsonList.getJSONObject(i);
			JSONObject insertObj1 = new JSONObject();
			insertObj1.put("goods_name",insertObj.getString("goods_name"));
			insertObj1.put("goods_sign",insertObj.getString("goods_sign"));
			insertObj1.put("goods_image_url",insertObj.getString("goods_image_url"));
			insertObj1.put("min_normal_price",insertObj.getString("min_normal_price"));
			insertObj1.put("min_group_price",insertObj.getString("min_group_price"));
			insertObj1.put("sales_tip",insertObj.getString("sales_tip"));
//			float price=Float.valueOf(insertObj.getString("min_group_price"));
//			float discount=Float.valueOf(insertObj.getString("coupon_discount"));
//			float quanhoujia=price-discount;
//			insertObj1.put("quanhoujia_price",quanhoujia);
			insertObj1.put("goods_id",insertObj.getString("goods_id"));
			insertObj1.put("promotion_rate",insertObj.getString("promotion_rate"));
			insertObj1.put("unified_tags",insertObj.getString("unified_tags"));
			insertObj1.put("coupon_discount",insertObj.getString("coupon_discount"));
			if (insertObj.containsKey("predict_promotion_rate")&&insertObj.getString("predict_promotion_rate").equals("0")) {
				insertObj1.put("is_bj","true");
			}
			dataList4.add(insertObj1);
		}
		int Total=Integer.valueOf(jsonObject.getJSONObject("goods_search_response").getString("total_count"));
		int zpage=Total/page_size;
		int yushu=Total%page_size;
		if(yushu>0){
			zpage=zpage+1;
		}
		res.setTotalCount(Total);
		res.setTotalPage(zpage);
		res.put("list_id",jsonObject.getJSONObject("goods_search_response").getString("list_id"));
		res.setResult("0");
		res.setDataList(dataList4);
		res.setResultNote("查询成功");
		return res;
	}


	/**
	 * 多多进宝搜索商品
	 * 排序方式:0-综合排序;1-按佣金比率升序;2-按佣金比例降序;3-按价格升序;4-按价格降序;5-按销量升序;6-按销量降序;7-优惠券金额排序升序;8-优惠券金额排序降序;9-券后价升序排序;10-券后价降序排序;11-按照加入多多进宝时间升序;12-按照加入多多进宝时间降序;13-按佣金金额升序排序;14-按佣金金额降序排序;15-店铺描述评分升序;16-店铺描述评分降序;17-店铺物流评分升序;18-店铺物流评分降序;19-店铺服务评分升序;20-店铺服务评分降序;27-描述评分击败同类店铺百分比升序，28-描述评分击败同类店铺百分比降序，29-物流评分击败同类店铺百分比升序，30-物流评分击败同类店铺百分比降序，31-服务评分击败同类店铺百分比升序，32-服务评分击败同类店铺百分比降序
	 * @param req
	 * @return
	 */
	@PostMapping("/pinduoduoWHPush")
	@ResponseBody
	public ResJson pinduoduoWHPush(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		res.put("mobile_url","");
		if (isBlank(req.getString("uid"))) {
			res.setResultNote("请先登录！");
			return res;
		}
		int page =0;
		int page_size=0;
		if (isBlank(req.getString("pageNo"))) {
			page=1;
		}else{
			page = Integer.parseInt(req.getString("pageNo"));
		}
		if (isBlank(req.getString("pageSize"))) {
			page_size=10;
		}else{
			page_size = Integer.parseInt(req.getString("pageSize"));
		}
		Member member=memberService.get(req.getString("uid"));
		if(member==null){
			res.setResult("1");
			res.setResultNote("用户不存在");
			return res;
		}
		if(isBlank(member.getPddId())){
			//调用喵有券创建推广位接口给当前用户生成一个推广位id
			Map<String, String> params12 = Maps.newHashMap();
			params12.put("pdname", MiaoyouquanUtils.pdname);
			params12.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params12);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						member.setPddId(pidList.getJSONObject(0).getString("p_id"));
						memberService.save(member);
					}
				}
			}
		}
		Map<String, String> params10 = Maps.newHashMap();
		Map<String, String> params11 = Maps.newHashMap();
		params10.put("pid",member.getPddId());
		params10.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		JSONObject jsonObject10 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.getauthority, params10);
		if (jsonObject10.containsKey("error_response")) {
			res.setResult("1");
			res.setResultNote("获取失败");
			return res;
		}
		if(jsonObject10.getJSONObject("authority_query_response").getString("bind").equals("0")){
			params11.put("channel_type","10");
			params11.put("p_id_list", "['"+member.getPddId()+"']");
			params11.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
			params11.put("generate_we_app","true");
			JSONObject jsonObject11 = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.addbnprom, params11);
			if (jsonObject10.containsKey("error_response")) {
				res.setResult("1");
				res.setResultNote("获取失败");
				return res;
			}
			res.setResult("0");
			res.setResultNote("未授权！");
			JSONObject url= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("mobile_url",url.getString("url"));
			JSONObject wxpay= (JSONObject) jsonObject11.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").get(0);
			res.put("we_app_info",wxpay.getJSONObject("we_app_info"));
			res.setTotalCount(0);
			res.setTotalPage(0);
			res.setResult("0");
			res.setDataList(new JSONArray());
			res.setResultNote("查询成功");
			return res;
		}
		Map<String, String> params = Maps.newHashMap();
		params.put("pid",member.getPddId());
		params.put("custom_parameters", "['uid':'"+req.getString("uid")+"','sid':'111']");
		params.put("sort_type",req.getString("sortType"));
//		0，最小成团价 1，券后价 2，佣金比例 3，优惠券价格 4，广告创建时间 5，销量 6，佣金金额 7，店铺描述分 8，店铺物流分 9，店铺服务分 10， 店铺描述分击败同行业百分比 11， 店铺物流分击败同行业百分比 12，店铺服务分击败同行业百分比 13，商品分 17 ，优惠券/最小团购价 18，过去两小时pv 19，过去两小时销量

		List<DictValue> Qhjlist = dictTypeService.get("a7cce03f03ed446fb711db8b8870313a").getDictValueList();//多多券后价
		String	jsonQhj="";
		if(Qhjlist.size()>=2){
			String QhjFrom=Qhjlist.get(0).getValue();
			String QhjTo=Qhjlist.get(1).getValue();
			if(QhjFrom.equals("0")||QhjTo.equals("0")){
				if(QhjTo.equals("0")){
					jsonQhj="{'range_id':'1','range_from':'"+QhjFrom+"'}";
				}else if(QhjFrom.equals("0")){
					jsonQhj="{'range_id':'1','range_to':'"+QhjTo+"'}";
				}
			}else{
				  jsonQhj="{'range_id':'1','range_from':'"+QhjFrom+"','range_to':'"+QhjTo+"'}";
			}
		}
		List<DictValue> Yhqlist = dictTypeService.get("472083cc72d340b08449bdc7df275218").getDictValueList();//多多优惠券
		String	jsonYhq="";
		if(Yhqlist.size()>=2){
			String YhqFrom=Yhqlist.get(0).getValue();
			String YhqTo=Yhqlist.get(1).getValue();
			if(YhqFrom.equals("0")||YhqTo.equals("0")){
				if(YhqTo.equals("0")){
					jsonYhq="{'range_id':'3','range_from':'"+YhqFrom+"'}";
				}else if(YhqFrom.equals("0")){
					jsonYhq="{'range_id':'3','range_to':'"+YhqTo+"'}";
				}
			}else{
				jsonYhq="{'range_id':'3','range_from':'"+YhqFrom+"','range_to':'"+YhqTo+"'}";
			}
		}
		List<DictValue> Ratelist = dictTypeService.get("e8a5929d7c3949518c0c53615bb9bab1").getDictValueList();//多多佣金
		String	jsonRate="";
		if(Ratelist.size()>=2){
			String RatejFrom=Ratelist.get(0).getValue();
			String RatejTo=Ratelist.get(1).getValue();
			if(RatejFrom.equals("0")||RatejTo.equals("0")){
				if(RatejTo.equals("0")){
					jsonRate="{'range_id':'6','range_from':'"+RatejFrom+"'}";
				}else if(RatejFrom.equals("0")){
					jsonRate="{'range_id':'6','range_to':'"+RatejTo+"'}";
				}
			}else{
				jsonRate="{'range_id':'6','range_from':'"+RatejFrom+"','range_to':'"+RatejTo+"'}";
			}
		}
		String rangeList="";
		if(jsonQhj.equals("")&&jsonYhq.equals("")&&jsonRate.equals("")){

			rangeList="[{'range_id':'6','range_from':'500'},{'range_id':'3','range_from':'10000'},{'range_id':'1','range_to':'10000'}]";
		}else{
			rangeList="["+jsonQhj+","+jsonYhq+","+jsonRate+"]";
		}
		params.put("range_list", rangeList);
		params.put("page",String.valueOf(page));
		params.put("page_size",String.valueOf(page_size));
		String list_id= RandomStringUtils.randomAlphanumeric(33);
		params.put("list_id", req.getString("list_id"));
		JSONObject jsonObject = PddUtils.duoduorouterAPI(PddUtils.router, PddUtils.searchgoods, params);
		if(jsonObject.containsKey("error_response")){
			res.setResultNote("获取失败！");
			return res;
		}
		JSONArray jsonList = jsonObject.getJSONObject("goods_search_response").getJSONArray("goods_list");
		JSONArray dataList4= new JSONArray();
		for(int i=0;i<jsonList.size();i++){
			// 遍历 jsonarray 数组，把每一个对象转成 json 对象
			JSONObject insertObj = jsonList.getJSONObject(i);
			JSONObject insertObj1 = new JSONObject();
			insertObj1.put("goods_name",insertObj.getString("goods_name"));
			insertObj1.put("goods_sign",insertObj.getString("goods_sign"));
			insertObj1.put("goods_image_url",insertObj.getString("goods_image_url"));
			insertObj1.put("min_normal_price",insertObj.getString("min_normal_price"));
			insertObj1.put("min_group_price",insertObj.getString("min_group_price"));
			insertObj1.put("sales_tip",insertObj.getString("sales_tip"));
//			float price=Float.valueOf(insertObj.getString("min_group_price"));
//			float discount=Float.valueOf(insertObj.getString("coupon_discount"));
//			float quanhoujia=price-discount;
//			insertObj1.put("quanhoujia_price",quanhoujia);
			insertObj1.put("goods_id",insertObj.getString("goods_id"));
			insertObj1.put("promotion_rate",insertObj.getString("promotion_rate"));
			insertObj1.put("unified_tags",insertObj.getString("unified_tags"));
			insertObj1.put("coupon_discount",insertObj.getString("coupon_discount"));
			if (insertObj.containsKey("predict_promotion_rate")&&insertObj.getString("predict_promotion_rate").equals("0")) {
				insertObj1.put("is_bj","true");
			}
			dataList4.add(insertObj1);
		}
		int Total=Integer.valueOf(jsonObject.getJSONObject("goods_search_response").getString("total_count"));
		int zpage=Total/page_size;
		int yushu=Total%page_size;
		if(yushu>0){
			zpage=zpage+1;
		}
		res.setTotalCount(Total);
		res.setTotalPage(zpage);
		res.put("list_id",jsonObject.getJSONObject("goods_search_response").getString("list_id"));
		res.setResult("0");
		res.setDataList(dataList4);
		res.setResultNote("查询成功");
		return res;
	}

	private String editTkl(String content) {
		return content.replaceAll(" +", "").length() > 30
				? content.replaceAll(" +", "").substring(0, 30) : content.replaceAll(" +", "");
	}
	/**
	 * 检测是否为空
	 * @param values
	 * @return
	 */
	private boolean isBlank(String...values) {
		for (String value : values) {
			if (StringUtils.isBlank(value)) {
				return true;
			}
		}
		return false;
	}
	/****
	 *
	 * 小程序登陆
	 *
	 * ***/
	@PostMapping("/wxapplogin")
	@ResponseBody
	public ResJson wxapplogin(@RequestBody ReqJson req) throws UnsupportedEncodingException {
		ResJson res = new ResJson();
		if (isBlank(req.getString("code"))) {
			res.setResultNote("code不能为空！");
			return res;
		}
		JSONObject json = WxAppOAuth.getOAuthLogin(req.getString("code"));
		if(json.containsKey("errcode")){
			res.put("errmsg",json.getString("errmsg"));
			return res;
		}
		String openid=json.getString("openid").replaceAll("\"", "");
		//判断存不存在openid如果存在就返回数据,一个状态判断
		Object member=memberService.executeGetSql("select id from t_member where wxAppOpenid='"+openid+"'");
		if(member==null){
			res.put("isOne","true");
		}else{
			res.put("isOne","false");
			//获取Uid
			String uid =member.toString();
			res.put("uid",uid);
		}
		//获取手机号
		//然后通过手机号获取会员信息
		res.put("session_key",json.getString("session_key").replaceAll("\"", ""));
		res.put("openid",openid);
		res.setResultNote("查询成功");
		res.setResult("0");
		return res;
	}
	/****
	 *
	 * 小程序TOKEN
	 *
	 * ***/
	@PostMapping("/getWxAccessToken")
	@ResponseBody
	public ResJson getWxAccessToken(@RequestBody ReqJson req) throws UnsupportedEncodingException {
		ResJson res = new ResJson();
		JSONObject json = WxAppOAuth.getAccessToken();
		if(json.containsKey("errcode")){
			res.put("errmsg",json.getString("errmsg"));
			return res;
		}
		res.put("access_token",json.getString("access_token").replaceAll("\\\\\"", ""));
		res.setResultNote("查询成功");
		res.setResult("0");
		return res;
	}
	/***
	 *小程序获取加密数据
	 ***/
	@PostMapping("/wxappEnCryData")
	@ResponseBody
	public ResJson wxappEnCryData(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		if (isBlank(req.getString("iv"))) {
			res.setResultNote("iv不能为空！");
			return res;
		}
		if (isBlank(req.getString("encryptedData"))) {
			res.setResultNote("encryptedData不能为空！");
			return res;
		}
		if (isBlank(req.getString("sessionKey"))) {
			res.setResultNote("sessionKey不能为空！");
			return res;
		}
		Object json = WxAppOAuth.getWxEnCryData(req.getString("encryptedData"),req.getString("sessionKey"),req.getString("iv"));
		Map<String, Object> userMap = JSONObject.parseObject(JSONObject.toJSONString(json));//转为map
		if(userMap==null){
			res.setResultNote("查询失败");
			return res;
		}
		res.put("data",userMap);
		res.setResultNote("查询成功");
		res.setResult("0");
		return res;
	}

	/**
	 * 小程序注册云网
	 * @param req
	 * @return
	 */
	@PostMapping("/wxappUserRegister")
	@ResponseBody
	public synchronized ResJson wxappUserRegister(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("注册失败");
		try {
			if (isBlank(req.getString("phoneNum"),req.getString("openid"))) {
				res.setResultNote("参数不完整");
				return res;
			}
			// 判断手机号是否可用//省市县，code
			if (!apiService.checkPhone(req.getString("phoneNum"))) {
				res.setResultNote("该手机号已存在");
				return res;
			}
			String invite = "35278AE6B4E14F1F9582937C5C836453";
			Member invitemember =null;
			if (StringUtils.isNotBlank(req.getString("inviteId"))) {
				invitemember = memberService.get(req.getString("inviteId"));
				invite = req.getString("inviteId");
			}
			if (invitemember == null) {
				invitemember = new Member(wohuiId);
			}
			// 调用三方
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Phone", req.getString("phoneNum")));
			list.add(new WohuiEntity("Code", req.getString("phoneNum")));
			list.add(new WohuiEntity("SenderGUID", invite));
			list.add(new WohuiEntity("Province", ""));
			list.add(new WohuiEntity("City", ""));
			list.add(new WohuiEntity("District", "", false));
			JSONObject object = WohuiUtils.send(WohuiUtils.PhoneReg, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);
			Member member = new Member();
			member.setIsNewRecord(true);
			member.setId(obj.getString("C_GUID"));
			member.setNumber(obj.getString("C_Number"));
			member.setRoles(obj.getString("C_Roles"));
			member.setPhone(req.getString("phoneNum"));
			member.setNickname("用户" + StringUtils.right(req.getString("phoneNum"), 4));
			member.setPassword(obj.getString("C_LoginPwd"));
			member.setProvince(req.getString("province"));
			member.setCity(req.getString("city"));
			member.setArea(req.getString("area"));
			member.setState("0");
			member.setOpenid(req.getString("openid"));
			member.setPoint("0");
			member.setInvite(invitemember);
			//调用喵有券创建推广位接口
			String pid="";
			Map<String, String> params = Maps.newHashMap();
			params.put("pdname", MiaoyouquanUtils.pdname);
			params.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						pid=pidList.getJSONObject(0).getString("p_id");
						member.setPddId(pid);
					}
				}
			}
			memberService.save(member);


			// 发送消息
			// 获取消息文案
			MsgExample msgExample = msgExampleService.getByType("1");
			if (msgExample != null) {
				msgService.insert(member, "系统消息", msgExample.getContent());
			}
			// 给邀请人发消息
			MsgExample example = msgExampleService.getByType("2");
			if (example != null) {
				msgService.insert(member.getInvite(), "系统消息", example.getContent());
			}
            //注册发送模版消息




            //注册
			res.put("pddId", pid);
			res.put("uid", member.getId());
			res.setResult("0");
			res.setResultNote("注册成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/**
	 * 小程序用户登录
	 * @param req
	 * @return
	 */
	@PostMapping("/wxappUserLogin")
	@ResponseBody
	public ResJson wxappUserLogin(@RequestBody ReqJson req) {
		ResJson res = new ResJson();
		res.setResultNote("登录失败");
		try {
				if (isBlank(req.getString("phoneNum"), req.getString("openid"))) {
					res.setResultNote("参数不完整");
					return res;
				}
				Member member = memberService.getByPhone(req.getString("phoneNum"));
				if(member==null){
					// 查询会员信息
					List<WohuiEntity> temp = Lists.newArrayList();
					temp.add(new WohuiEntity("Phone", req.getString("phoneNum")));
					JSONObject jsonObject = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, temp);
					if (!"0000".equals(jsonObject.getString("respCode"))) {
						res.setResultNote(jsonObject.getString("respMsg"));
						return res;
					}
					JSONArray jsonArray = jsonObject.getJSONArray("data");
					JSONObject o = jsonArray.getJSONObject(0);
					member = new Member();
					member.setNumber(o.getString("C_Number"));
					member.setPhone(o.getString("phoneNum"));
					member.setIsNewRecord(true);
					member.setId(o.getString("C_GUID"));
					member.setNumber(o.getString("C_Number"));
					member.setRoles(o.getString("C_Roles"));
					member.setPhone(o.getString("C_Phone"));
					member.setNickname(StringUtils.isNotBlank(o.getString("C_RealName")) ? o.getString("C_RealName") : "用户" + StringUtils.right(o.getString("C_Phone"), 4));
					member.setPassword(o.getString("C_LoginPwd"));
					member.setProvince(o.getString("C_Province"));
					member.setCity(o.getString("C_City"));
					member.setArea(o.getString("C_District"));
					member.setState("0");
					member.setPoint("0");
					//清除绑定的openid
					String wxAppOpenid=req.containsKey("openid")?req.getString("openid"):"";
					if(!wxAppOpenid.equals("")){
						String meobject= (String) memberService.executeGetSql("select id from t_member where wxAppOpenid='"+wxAppOpenid+"'");
						if(meobject!=null&&!meobject.equals("")){
							Member meojects=memberService.get(meobject);
							meojects.setWxAppOpenid("");
							memberService.save(meojects);
						}
					}
					member.setWxAppOpenid(wxAppOpenid);
					//ene
					member.setInvite(new Member(o.getString("C_Sender")));
					memberService.save(member);
				}else{
					//清除绑定的openid
					String wxAppOpenid=req.containsKey("openid")?req.getString("openid"):"";
					if(!wxAppOpenid.equals("")){
						String meobject= (String) memberService.executeGetSql("select id from t_member where wxAppOpenid='"+wxAppOpenid+"'");
						if(meobject!=null&&!meobject.equals("")){
							Member meojects=memberService.get(meobject);
							meojects.setWxAppOpenid("");
							memberService.save(meojects);
						}
					}
					member.setWxAppOpenid(wxAppOpenid);
					//ene
					memberService.save(member);
				}

			res.put("uid", member.getId());
			res.setResult("0");
			res.setResultNote("登录成功");
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return res;
	}
	/***
	 *小程序获取手机号
	 ***/
	@PostMapping("/wxappPhone")
	@ResponseBody
	public ResJson wxappphone(@RequestBody ReqJson req){
		ResJson res = new ResJson();
		if (isBlank(req.getString("iv"))) {
			res.setResultNote("iv不能为空！");
			return res;
		}
		if (isBlank(req.getString("encryptedData"))) {
			res.setResultNote("encryptedData不能为空！");
			return res;
		}
		if (isBlank(req.getString("sessionKey"))) {
			res.setResultNote("sessionKey不能为空！");
			return res;
		}
		if (req.getString("openid").equals("")) {
			res.setResultNote("openid不能为空！");
			return res;
		}
		Object json = WxAppOAuth.getWxEnCryData(req.getString("encryptedData"),req.getString("sessionKey"),req.getString("iv"));
		Map<String, Object> userMap = JSONObject.parseObject(JSONObject.toJSONString(json));//转为map
		if(!userMap.containsKey("phoneNumber")){
			res.setResultNote("解密失败手机号不存在");
			return res;
		}
		/******************************************************************************/
		res.put("phoneNum",userMap.get("phoneNumber"));//返回
		res.setResultNote("查询成功！");
		req.put("phoneNum",userMap.get("phoneNumber"));
		String invite = "35278AE6B4E14F1F9582937C5C836453";
		Member invitemember =null;
		if (StringUtils.isNotBlank(req.getString("inviteId"))) {
			invitemember = memberService.get(req.getString("inviteId"));
			invite = req.getString("inviteId");
		}
		if (invitemember == null) {
			invitemember = new Member(wohuiId);
		}
		// 调用三方
		List<WohuiEntity> list = Lists.newArrayList();
		String phone=req.getString("phoneNum");
		list.add(new WohuiEntity("Phone", phone));
		list.add(new WohuiEntity("Code", phone.substring(phone.length()-6)));
		list.add(new WohuiEntity("SenderGUID", invite));
		list.add(new WohuiEntity("Province", ""));
		list.add(new WohuiEntity("City", ""));
		list.add(new WohuiEntity("District", "", false));

		//判断是否可以登陆
		List<WohuiEntity> entityList = Lists.newArrayList();
		entityList.add(new WohuiEntity("Phone", userMap.get("phoneNumber").toString()));
		JSONObject Uobject = WohuiUtils.send(WohuiUtils.GetUInfoByPhone, entityList);
		if (!"0000".equals(Uobject.getString("respCode"))) {
			JSONObject object = WohuiUtils.send(WohuiUtils.PhoneReg, list);
			if (!"0000".equals(object.getString("respCode"))) {
				res.setResultNote(object.getString("respMsg"));
				return res;
			}
			JSONArray data = object.getJSONArray("data");
			JSONObject obj = data.getJSONObject(0);
			Member member = new Member();
			member.setIsNewRecord(true);
			member.setId(obj.getString("C_GUID"));
			member.setNumber(obj.getString("C_Number"));
			member.setRoles(obj.getString("C_Roles"));
			member.setPhone(req.getString("phoneNum"));
			member.setNickname("用户" + StringUtils.right(req.getString("phoneNum"), 4));
			member.setPassword(obj.getString("C_LoginPwd"));
			member.setProvince(req.getString("province"));
			member.setCity(req.getString("city"));
			member.setArea(req.getString("area"));
			member.setState("0");
			//清除绑定的openid
			String wxAppOpenid=req.containsKey("openid")?req.getString("openid"):"";
			if(!wxAppOpenid.equals("")){
				String meobject= (String) memberService.executeGetSql("select id from t_member where wxAppOpenid='"+wxAppOpenid+"'");
				if(meobject!=null&&!meobject.equals("")){
					Member meojects=memberService.get(meobject);
					meojects.setWxAppOpenid("");
					memberService.save(meojects);
				}
			}
			member.setWxAppOpenid(wxAppOpenid);
			//ene
			member.setPoint("0");
			member.setInvite(invitemember);
			//调用喵有券创建推广位接口
			String pid="";
			Map<String, String> params = Maps.newHashMap();
			params.put("pdname", MiaoyouquanUtils.pdname);
			params.put("number", "1");
			JSONObject jsonObject = MiaoyouquanUtils.miaoyouquanAPI(MiaoyouquanUtils.docreatepddpid, params);
			logger.debug("喵有券返回数据：" + jsonObject.toString());
			if ("200".equals(jsonObject.getString("code"))) {
				JSONObject dataObject=jsonObject.getJSONObject("data");
				if(dataObject!=null){
					JSONArray pidList=dataObject.getJSONArray("p_id_list");
					if(pidList!=null && pidList.size()>0){
						pid=pidList.getJSONObject(0).getString("p_id");
						member.setPddId(pid);
					}
				}
			}
			memberService.save(member);


			// 发送消息
			// 获取消息文案
			MsgExample msgExample = msgExampleService.getByType("1");
			if (msgExample != null) {
				msgService.insert(member, "系统消息", msgExample.getContent());
			}
			// 给邀请人发消息
			MsgExample example = msgExampleService.getByType("2");
			if (example != null) {
				msgService.insert(member.getInvite(), "系统消息", example.getContent());
			}
			res.setResultNote("注册成功！");
		}
		/******************************************************************************/
		res.setResult("0");
		return res;
	}
}